import { defineStore } from 'pinia';
import { ref } from 'vue';
import { ACCOUNT_LOGIN, GET_USER_INFO_BY_ID, GET_USER_MENU_BY_ROLE_ID } from '@/api';
import { ElMessage } from 'element-plus';
import type { IAccount, IUserInfo } from '@/types/login';
import { storage } from '@/utils/storage-util';
import router from '@/router';
import { LOGIN_TOKEN } from '@/global/constants';
import { mapMenusToPermissions, mapMenusToRoutes } from '@/utils/map-menus';
import { useMainStore } from '@/store/mian';

export const useLoginStore = defineStore('login', () => {
  const token = ref<string>();
  const userInfo = ref<IUserInfo>();
  const userMenus = ref<any>();
  const statePermissions = ref<string[]>();

  /**
   * @function loginByAccountAction 使用账号密码登录
   * @param account 账号对象，包含了账号和密码
   */
  const loginByAccountAction = async (account: IAccount) => {
    try {
      const loginRes = await ACCOUNT_LOGIN(account);
      // resType: {id: number, name: string, token: string}
      token.value = loginRes.token;

      // 1.保存token
      storage.set(LOGIN_TOKEN, token.value);
      ElMessage.success('登录成功');

      // 2.调用接口，获取用户的详细信息
      const userInfoRes = await GET_USER_INFO_BY_ID(loginRes.id);

      // 3.接口返回正确的数据才存入userInfo，再进行跳转
      storage.set('userInfo', userInfoRes);
      ElMessage.success('获取用户信息成功');

      // 4.获取用户的权限
      const menuInfoRes = await GET_USER_MENU_BY_ROLE_ID(userInfoRes.role.id);
      userMenus.value = menuInfoRes;

      // 5.保存用户权限
      storage.set('userMenu', menuInfoRes);
      ElMessage.success('获取用户权限成功');

      const mainStore = useMainStore();
      await mainStore.actionFetchEntireData();

      // 6.将用户权限转换为路由
      const routes = mapMenusToRoutes(userMenus.value);
      routes.forEach((route) => router.addRoute('main', route));
      // 获取登录用户的所有按钮的权限
      statePermissions.value = mapMenusToPermissions(userMenus.value);

      // 7.跳转首页
      await router.push('/main');
    } catch (err) {
      console.warn(err);
      if (typeof err === 'string') {
        ElMessage.error(err);
      }
    }
  };

  /**
   * @function loadLocalCacheAction 加载缓存用户相关数据
   */
  const loadLocalCacheAction = () => {
    const cacheToken = storage.get(LOGIN_TOKEN);
    const cacheUserInfo = storage.get<IUserInfo>('userInfo', true) as IUserInfo | null;
    const cacheUserMenu = storage.get<any[]>('userMenu', true) as any[] | null;
    // 这三个值，同时有值的情况下就说明用户一定登录了
    if (cacheToken && cacheUserInfo && cacheUserMenu) {
      // 防止用户刷新时，用户信息被清空了
      const mainStore = useMainStore();
      mainStore.actionFetchEntireData();
      token.value = cacheToken;
      userInfo.value = cacheUserInfo;
      userMenus.value = cacheUserMenu;
      // 防止刷新后权限被清空了
      statePermissions.value = mapMenusToPermissions(cacheUserMenu);
      const routes = mapMenusToRoutes(cacheUserMenu);
      routes.forEach((route) => router.addRoute('main', route));
    }
  };

  return {
    token,
    userInfo,
    userMenus,
    statePermissions,
    loginByAccountAction,
    loadLocalCacheAction
  };
});
